use chrono::NaiveDateTime;
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};

#[derive(
    Debug, Clone, PartialEq, DeriveEntityModel, DerivePartialModel, Eq, Serialize, Deserialize,
)]
#[sea_orm(table_name = "sys_login_log")]
#[sea_orm(entity = "Entity")]
pub struct Model {
    #[sea_orm(primary_key)]
    pub id: i32,
    #[sea_orm(column_type = "String(StringLen::N(64))")]
    pub username: String,
    /// - 0：登陆成功
    /// - 1：用户不存在或密码错误
    pub result: i8,
    pub user_ip: String,
    pub user_agent: String,
    pub created_at: NaiveDateTime,
}

#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}

#[async_trait::async_trait]
impl ActiveModelBehavior for ActiveModel {
    /// Will be called before `ActiveModel::insert`, `ActiveModel::update`, and `ActiveModel::save`
    async fn before_save<C>(mut self, _db: &C, insert: bool) -> Result<Self, DbErr>
    where
        C: ConnectionTrait,
    {
        if insert {
            let current = crate::util::current_datetime();
            self.created_at = sea_orm::Set(current);
        }
        Ok(self)
    }
}
